class GitUtil:
    def __init__(self, repo_path='.'):  # 修改初始化方法
        self.repo_path = repo_path

    def git_pull(self):
        """拉取仓库最新代码"""
        try:
            import subprocess
            result = subprocess.run(['git', 'pull'], check=True,
                                    capture_output=True, text=True,
                                    cwd=self.repo_path)
            return result.returncode == 0
        except (subprocess.CalledProcessError, Exception) as e:
            print(f"拉取代码失败: {str(e)}")
            return False

    def get_tags_list(self):
        """获取仓库tags列表（按版本排序）"""
        try:
            import subprocess
            # 先获取所有远程tag
            subprocess.run(['git', 'fetch', '--tags'], check=True,
                           cwd=self.repo_path)

            output = subprocess.check_output(
                ['git', 'tag', '-l', '--sort=-version:refname'],
                text=True,
                cwd=self.repo_path  # 新增路径参数
            )
            return output.strip().split('\n')
        except (subprocess.CalledProcessError, Exception) as e:
            print(f"获取tags失败: {str(e)}")
            raise e

    def checkout_tag(self, tag_name):
        """切换到指定tag代码"""
        try:
            import subprocess
            result = subprocess.run(['git', 'checkout', tag_name],
                                    check=True, capture_output=True,
                                    text=True, cwd=self.repo_path)
            return result.returncode == 0
        except (subprocess.CalledProcessError, Exception) as e:
            print(f"切换tag失败: {str(e)}")
            return False

    def get_current_branch(self):
        """获取当前所在分支名称"""
        try:
            import subprocess
            output = subprocess.check_output(
                ['git', 'branch', '--show-current'],
                text=True,
                cwd=self.repo_path
            )
            return output.strip() or None
        except (subprocess.CalledProcessError, Exception) as e:
            print(f"获取分支失败: {str(e)}")
            return None

    def checkout_branch(self, branch_name):
        """切换到指定分支"""
        try:
            import subprocess
            result = subprocess.run(
                ['git', 'checkout', branch_name],
                check=True,
                capture_output=True,
                text=True,
                cwd=self.repo_path
            )
            return result.returncode == 0
        except (subprocess.CalledProcessError, Exception) as e:
            print(f"切换分支失败: {str(e)}")
            return False

    def discard_repo_changes(self):
        """强制重置指定Git仓库（类方法）"""
        try:
            import subprocess
            subprocess.run(['git', 'reset', '--hard', 'HEAD'],
                           check=True, cwd=self.repo_path)
            subprocess.run(['git', 'clean', '-df'],
                           check=True, cwd=self.repo_path)
            return True
        except Exception as e:
            print(f"仓库 {self.repo_path} 重置失败: {str(e)}")
            return False
